<template>
	<div class="dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" :close-on-click-modal="false" width="500px">
			<el-form ref="formRef" :model="state.ruleForm" :rules="state.rules">
				<el-row class="mb20">
					<el-col>
						<el-form-item label="所属上级" prop="parent_id">
							<el-tree-select
								v-model="state.ruleForm.parent_id"
								:data="state.treeSelectData"
								:cache-data="state.cacheData"
								:props="state.parentIdProps"
								:load="parentIdloadNode"
								check-strictly
								lazy
								clearable
								@node-click="onParentIdNode"
								class="w100"
							/>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row class="mb20">
					<el-col>
						<el-form-item label="地区名称" prop="name">
							<el-input v-model="state.ruleForm.name" placeholder="请输入地区名称" clearable />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col>
						<el-form-item label="排序" prop="display_order">
							<el-input v-model="state.ruleForm.display_order" placeholder="请输入排序" clearable @input="onVerifiyNumberIntegerDisplayOrder" />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<el-button @click="onCancel" size="default">取 消</el-button>
				<el-button type="primary" @click="onSubmit" :loading="state.dialog.submitLoading" size="default">提 交</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import { ElMessage } from 'element-plus';
import { nextTick, reactive, ref } from 'vue';
import { areaApi } from '/@/api';
import { verifiyNumberInteger } from '/@/utils/toolsValidate';

let callback: Function = () => {};
let _node: any = null;
let _resolve: any = null;
const AreaApi = areaApi();
const state = reactive({
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitLoading: false,
	},
	ruleForm: {
		parent_id: '',
		name: '',
		level: '',
		display_order: '',
	},
	rules: {
		name: [{ required: true, message: '地区名称不能为空', trigger: ['blur'] }],
	},
	parentIdProps: {
		value: 'id',
		label: 'name',
		children: 'children',
	},
	treeSelectData: [],
	cacheData: [] as any,
});
const formRef = ref();

/********** 触发事件 **********/
// 点击某个节点
const onParentIdNode = (data: any) => {
	state.ruleForm.level = data.level + 1;
	console.log(state.ruleForm);
};
// 排序过滤
const onVerifiyNumberIntegerDisplayOrder = (val: string) => {
	state.ruleForm.display_order = verifiyNumberInteger(val);
};
// 取消
const onCancel = () => {
	state.dialog = {
		isShowDialog: false,
		type: '',
		title: '',
		submitLoading: false,
	};
};
// 提交
const onSubmit = () => {
	formRef.value.validate((valid: boolean) => {
		if (!valid) return;
		state.dialog.submitLoading = true;
		if (state.dialog.type === 'add') {
			_areaAdd({
				...state.ruleForm,
				level: state.ruleForm.level === '' ? 0 : state.ruleForm.level,
			});
		} else {
			_areaEdit({
				...state.ruleForm,
				level: state.ruleForm.level === '' ? 0 : state.ruleForm.level,
			});
		}
	});
};

/********** 方法事件 **********/
// 打开
const openDialog = (data: any, row: any, fn: Function) => {
	state.dialog = {
		isShowDialog: true,
		type: data.type,
		title: data.title,
		submitLoading: false,
	};
	callback = fn;
	if (_node) {
		_node.childNodes = [];
		parentIdloadNode(_node, _resolve);
	}
	nextTick(() => {
		formRef.value.resetFields();
		if (state.dialog.type !== 'add') {
			_areaInfo({ area_id: row.id }, 1);
			row.parent_id && _areaInfo({ area_id: row.parent_id }, 0);
		}
	});
};
// 请求节点
const parentIdloadNode = (node: any, resolve: (arg0: any) => void) => {
	if (!node.level) {
		_node = node;
		_resolve = resolve;
	}
	_areaList({ parent_id: node.level ? node.data.id : 0 }, node.level, resolve);
};

/********** 网络请求 **********/
// 国家地区列表
const _areaList = (params: Object, level: number, resolve: (arg0: any) => void) => {
	AreaApi.areaList(params).then((res: any) => {
		let nodes = res.data.list.map((item: any) => ({
			id: item.id,
			name: item.name,
			level: item.level,
			leaf: level >= 2,
		}));
		resolve(nodes);
	});
};
// 获取国家地区信息
const _areaInfo = (params: Object, level: number) => {
	AreaApi.areaInfo(params).then((res: any) => {
		if (level) {
			state.ruleForm = {
				...res.data.info,
				area_id: res.data.info.id,
			};
		} else {
			state.cacheData = [res.data.info];
		}
	});
};
// 添加国家地区
const _areaAdd = (params: Object) => {
	AreaApi.areaAdd(params)
		.then(() => {
			ElMessage.success('操作成功！');
			onCancel();
			callback();
		})
		.catch(() => (state.dialog.submitLoading = false));
};
// 編輯国家地区
const _areaEdit = (params: Object) => {
	AreaApi.areaEdit(params)
		.then(() => {
			ElMessage.success('操作成功！');
			onCancel();
			callback();
		})
		.catch(() => (state.dialog.submitLoading = false));
};

/********** 方法向父组件暴露 **********/
defineExpose({ openDialog });
</script>
